<template>
  <div class="app-container">
    <el-row :gutter="30">
      <el-col :span="4" style="border-right:1px solid #dcdfe6;height:700px">
        <el-input
          placeholder="输入组织名称"
          size="small" style="margin-bottom:30px;margin-top:10px"
          @keyup.enter.native="searchTreeData"
          v-model="treeSearchInputValue"
          clearable>
        </el-input>
        <el-tree :data="treeData" :props="defaultProps" @node-click="handleNodeClick" empty-text="暂无数据"
                 :default-expanded-keys="defaultExpandedKeys" :load="loadChildren" lazy highlight-current
                 node-key="id"></el-tree>
      </el-col>
      <el-col :span="20">
        <div style="margin-top:10px">
          <el-button icon="el-icon-plus" type="primary" size="mini" @click="addData" v-if="p1">新增</el-button>
          <el-button icon="el-icon-close" type="danger" size="mini" @click="deleteAny" v-if="p4">删除</el-button>
        </div>
        <div class="query-form">
          <el-form ref="tableSearchParam" :model="tableSearchParam" label-width="50px" :inline="true">
            <!--<el-form-item label="父组织名称" label-width="90px">-->
            <!--<el-input v-model="tableSearchParam.name" style="width:200px" size="small"></el-input>-->
            <!--</el-form-item>-->
            <el-form-item label="姓名" label-width="70px">
              <el-input v-model="tableSearchParam.name" style="width:200px" size="small"></el-input>
            </el-form-item>
            <el-form-item label="手机号码" label-width="90px">
              <el-input v-model="tableSearchParam.telphone" style="width:200px" size="small"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="listTableData" icon="el-icon-search" size="small">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <br/>
        <el-table
          :data="tableData"
          border
          empty-text="暂无数据"
          style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            width="35">
          </el-table-column>
          <el-table-column
            label="用户名"
            property="username"
            width="80">
          </el-table-column>
          <el-table-column
            label="姓名"
            property="name"
            width="100">
          </el-table-column>
          <el-table-column
            label="手机号码"
            property="telphone"
            width="100">
          </el-table-column>
          <el-table-column
            property="createdTime"
            label="创建时间"
            width="140">
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                icon="el-icon-edit"
                type="success"
                v-if="p2"
                @click="editData(scope.$index, scope.row)">编辑
              </el-button>
              <el-button
                size="mini"
                icon="el-icon-setting"
                v-if="p5"
                @click="editPassword(scope.$index, scope.row)">修改密码
              </el-button>
              <el-button
                size="mini"
                icon="el-icon-lemone-user_role"
                type="warning"
                v-if="p3"
                @click="allocateRole(scope.$index, scope.row)">分配角色
              </el-button>
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-close"
                v-if="p4 && currentUserId!=scope.row.id"
                @click="handleDelete(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="page">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page=this.currentPage
            :page-sizes="[10, 20, 30, 40]"
            :page-size=this.pageSize
            layout="total, sizes, prev, pager, next, jumper"
            :total=this.total>
          </el-pagination>
        </div>
      </el-col>
    </el-row>
    <el-dialog title="修改密码" :visible.sync="dialogFormVisible" top="10vh">
      <el-form :model="updatePasswordData" style="width:400px" :rules="rules" ref="ruleForm">
        <el-form-item label="旧密码" :label-width="formLabelWidth">
          <el-input type="password" v-model="updatePasswordData.oldPassword" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="新密码" :label-width="formLabelWidth" prop="newPassword">
          <el-input type="password" v-model="updatePasswordData.newPassword" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" :label-width="formLabelWidth" prop="comfirmPassword">
          <el-input type="password" v-model="updatePasswordData.comfirmPassword" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handlePassword">修改</el-button>
      </div>
    </el-dialog>
    <el-dialog title="分配角色" :visible.sync="dialogRoleFormVisible" top="10vh">
      <div style="margin-left: 50px">
        <el-transfer v-model="selectRole" :data="noSelectRole" :titles="title"
                     :props="{key: 'id',label: 'name'}"></el-transfer>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRoleFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAllocateRole" :loading="loading">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss">
  .page {
    text-align: center;
    margin-top: 20px;
  }

  .query-form {
    border-bottom: 1px solid #ebeef5;
    padding-top: 25px;
  }
</style>

<script>
  import organizationApi from '@/api/organizationApi'
  import userApi from '@/api/userApi'
  import {isValidPassword} from '@/common/validate'
  import organization2roleApi from '@/api/organization2roleApi'
  import user2roleApi from '@/api/user2roleApi'
  import store from '../../../store'

  export default {
    created() {
      this.p1 = this.permissionValid.validAction(this.permissionValid.permissionRule.user.addUser)
      this.p2 = this.permissionValid.validAction(this.permissionValid.permissionRule.user.updateUser)
      this.p3 = this.permissionValid.validAction(this.permissionValid.permissionRule.user2role.saveUser2Role)
      this.p4 = this.permissionValid.validAction(this.permissionValid.permissionRule.user.removeUser)
      this.p5 = this.permissionValid.validAction(this.permissionValid.permissionRule.user.updatePassword)
      this.initData()
      this.currentUserId = store.getters.token
    },
    data() {
      const validatePassword = (rule, value, callback) => {
        if (this.updatePasswordData.newPassword != '' && this.updatePasswordData.comfirmPassword) {
          if (!isValidPassword(this.updatePasswordData.newPassword, this.updatePasswordData.comfirmPassword)) {
            callback(new Error('密码输入不一致'))
          } else {
            callback()
          }
        }
      }
      return {
        currentUserId: '',
        p1: false,
        p2: false,
        p3: false,
        p4: false,
        p5: false,
        title: ['未分配角色', '已分配角色'],
        noSelectRole: [],
        selectRole: [],
        allData: [],
        tableData: [],
        currentPage: 1,
        pageSize: 10,
        total: 0,
        tableSearchParam: {
          name: '',
          telphone: ''
        },
        treeData: [],
        treeSearchInputValue: '',
        treeSearchParam: {},
        defaultProps: {
          children: 'children',
          label: 'label',
          isLeaf: 'leaf'
        },
        loading: false,
        actionType: '',
        defaultExpandedKeys: [],
        multipleSelection: [],
        dialogFormVisible: false,
        formLabelWidth: '80px',
        updatePasswordData: {
          id: '',
          oldPassword: '',
          newPassword: '',
          comfirmPassword: ''

        },
        userId: '',
        dialogRoleFormVisible: false,
        rules: {
          newPassword: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {min: 6, max: 50, message: '长度在 6 到 50 个字符', trigger: 'blur'},
            {trigger: 'blur', validator: validatePassword},
          ],
          comfirmPassword: [
            {required: true, message: '请输入确认密码', trigger: 'blur'},
            {min: 6, max: 50, message: '长度在 6 到 50 个字符', trigger: 'blur'},
            {trigger: 'blur', validator: validatePassword},
          ]
        },
      }
    },
    methods: {
      initData() {
        this.listTableData()

        this.treeSearchParam = {}
        this.treeSearchParam.parentId = ''
        this.listTreeData()
      },
      listTreeData() {
        organizationApi.listAllOrganization(this.treeSearchParam, (res) => {
          this.treeData = res
          for (var td of res) {
            this.defaultExpandedKeys.push(td.id)
          }
        }, () => {
        })
      },
      loadChildren(node, resolve) {
        if (node.level === 0) {
          return resolve(this.treeData)
        }
        this.treeSearchParam = {}
        this.treeSearchParam.parentId = node.data.id
        organizationApi.listAllOrganization(this.treeSearchParam, (res) => {
          resolve(res)
        }, () => {
        })
      },
      listTableData() {
        userApi.listUser(this.tableSearchParam, this.currentPage, this.pageSize, (res) => {
          this.tableData = res.list
          this.total = res.total
        }, () => {
        })
      },
      handleNodeClick(data) {
        this.tableSearchParam = {}
        this.tableSearchParam.organizationId = data.id
        this.currentPage = 1
        this.pageSize = 10
        this.listTableData()
      },
      addData() {
        this.$router.push({path: '/system/user/info/add'})
      },
      editData(index, row) {
        this.$router.push({path: '/system/user/info/edit?id=' + row.id})
      },
      editPassword(index, row) {
        this.dialogFormVisible = true
        this.updatePasswordData.id = row.id
      },
      handlePassword() {
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            userApi.updatePassword(this.updatePasswordData, (res) => {
              this.loading = false
              this.$message({
                message: '修改密码成功',
                type: 'success'
              })
            }, () => {
              this.loading = false
              this.dialogFormVisible = false
            })
          }
        })
      },
      handleDelete(index, row) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          userApi.deleteSingleUser(row.id, (res) => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.listTableData()
          }, () => {
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
      ,
      handleSizeChange(val) {
        this.pageSize = val
        this.listTableData()
      }
      ,
      handleCurrentChange(val) {
        this.currentPage = val
        this.listTableData()
      }
      ,
      searchTreeData() {
        this.treeSearchParam = {}
        if (this.treeSearchInputValue == '') {
          this.treeSearchParam.parentId = ''
        } else {
          this.treeSearchParam.name = this.treeSearchInputValue
        }
        this.listTreeData()
      }
      ,
      searchTableData() {

      }
      ,
      handleSelectionChange(val) {
        this.multipleSelection = []
        for (var ms of val) {
          this.multipleSelection.push(ms.id)
        }
      }
      ,
      deleteAny() {
        if (this.multipleSelection.length == 0) {
          this.$message({
            type: 'warning',
            message: '请选择记录!'
          })
          return;
        }
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          userApi.deleteUser(this.multipleSelection, (res) => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.listTableData()
          }, () => {
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      allocateRole(index, row) {
        this.noSelectRole = []
        this.selectRole = []
        const loadings = this.$loading({
          lock: true,
          text: '拼命加载中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        organization2roleApi.listRoleSelectd(row.organizationIds.split(','), (res) => {
          this.noSelectRole = res
          user2roleApi.listRoleSelectd(row.id, (res) => {
            for (var r of res) {
              this.selectRole.push(r.id)
            }
            this.userId = row.id
            this.dialogRoleFormVisible = true
            loadings.close()
          }, () => {
            loadings.close()
          })
        }, () => {
        })
      },
      handleAllocateRole() {
        let param = {
          user_id: this.userId,
          role_ids: this.selectRole
        }
        this.loading = true
        user2roleApi.saveUser2Role(param, (res) => {
          this.loading = false
          this.dialogRoleFormVisible = false
          this.$message({
            message: '角色分配成功',
            type: 'success'
          })
        }, () => {
          this.loading = false
        })
      }
    }
  }
</script>
